package ex11.pyrmont.startup;

//use StandardWrapper
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.connector.http.HttpConnector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.loader.WebappLoader;

import ex11.pyrmont.core.SimpleContextConfig;

public final class Bootstrap {
	public static void main(String[] args) {

		// invoke: http://localhost:8080/Modern or
		// http://localhost:8080/Primitive

		System.setProperty("catalina.base", System.getProperty("user.dir"));
		HttpConnector connector = new HttpConnector();
		StandardWrapper wrapper1 = new StandardWrapper();
		wrapper1.setName("Primitive");
		wrapper1.setServletClass("PrimitiveServlet");
		StandardWrapper wrapper2 = new StandardWrapper();
		wrapper2.setName("Modern");
		wrapper2.setServletClass("ModernServlet");

		StandardContext context = new StandardContext();
		// StandardContext's start method adds a default mapper
		context.setPath("/myApp");
		context.setDocBase("myApp");
		LifecycleListener listener = new SimpleContextConfig();
		((Lifecycle) context).addLifecycleListener(listener);

		context.addChild(wrapper1);
		context.addChild(wrapper2);
		// for simplicity, we don't add a valve, but you can add
		// valves to context or wrapper just as you did in Chapter 6

		WebappLoader loader = new WebappLoader();
		context.setLoader(loader);
		// context.addServletMapping(pattern, name);
		context.addServletMapping("/Primitive", "Primitive");
		context.addServletMapping("/Modern", "Modern");
		// add ContextConfig. This listener is important because it configures
		// StandardContext (sets configured to true), otherwise StandardContext
		// won't start
		connector.setContainer(context);
		try {
			connector.initialize();
			(connector).start();
			(context).start();

			// make the application wait until we press a key.
			System.in.read();
			((Lifecycle) context).stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}